/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package io.netty.example.echo;

import java.util.Scanner;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * Handler implementation for the echo client. It initiates the ping-pong
 * traffic between the echo client and server by sending the first message to
 * the server.
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		ctx.writeAndFlush(NettyUtil.appenEndOfLine("我要连接...."));
		new Thread(new Hander(ctx)).start();
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) {
		try {
			System.out.println(msg);
		} finally {
			// 读完消息记得释放，那写消息为什么不这样操作呢，因为写完消息netty自动释放。
			// 其操作见：DefaultChannelHandlerInvoker L331-332,不过有这个注释-> promise
			// cancelled
			// 是不少netty5正式发布的时候会取消呢。
			// 我们可以使用SimpleChannelInboundHandler作为父类，因为释放操作已实现。
			ReferenceCountUtil.release(msg);
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		// Close the connection when an exception is raised.
		cause.printStackTrace();
		ctx.close();
	}

	private static class Hander implements Runnable {
		private ChannelHandlerContext ctx = null;
		private Scanner scanner = new Scanner(System.in);

		public Hander(ChannelHandlerContext ctx) {
			this.ctx = ctx;
		}

		@Override
		public void run() {
			while (true) {
				String nextLine = scanner.nextLine();
				ctx.writeAndFlush(NettyUtil.appenEndOfLine(nextLine));
			}

		}
	}
}
